package com.woniuxy.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.memory.redis.RedisChatMemoryRepository;
import com.woniuxy.rag.FileProcessVectorTools;
import com.woniuxy.service.DeadMessageServiceTools;
import com.woniuxy.service.UserService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 25/10/22/星期三 14:57
 * @Component: 成都蜗牛学苑
 **/
@RestController
@RequestMapping("/ai")
@CrossOrigin
public class AiChatController {
    @Autowired
    DeadMessageServiceTools deadMessageServiceTools;
    @Autowired
    ChatClient chatClient;
    @Autowired
    UserService userService;
    @Value("${woniu.filePathTmp}")
    String path;
    @Autowired
    PgVectorStore vectorStore;
    @Autowired
    FileProcessVectorTools fileProcessVectorTools;
    //produces 响应体的媒体类型,SSE格式，data:文本 data:文本
    @PostMapping(value = "/stream",produces = "text/event-stream")
    public Flux<Generation> stream(@RequestBody String msg){
        //这个代码 要用advisor封装
        //在内存中，根据文本向量化，查询最相似的文档
        List<Document> documents = vectorStore.similaritySearch(SearchRequest.builder()
                .query(msg)
                .topK(2) // 返回前2个最相似的文档
                .similarityThreshold(0.5) // 相似度阈值，默认0.75，只有相似度大于等于该值才会返回
                .build());
        System.out.println(documents);
        //stream流式，content自动处理流式响应的文本
        return chatClient.prompt(documents + "，请根据以上文档，回答我的问题：" + msg).advisors(advisor->advisor.param("chat_memory_conversation_id","会话id"))
                //局部的工具配置
                .tools(deadMessageServiceTools,fileProcessVectorTools)
                .stream().chatResponse().map(ChatResponse::getResult);
    }
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file){
        try {
            //1.先判断有没有这个静态资源路径
            if (Files.notExists(Paths.get(path))) {
                //2.如果没有文件夹就创建 递归创建
                Files.createDirectories(Paths.get(path));
            }
            //自动创建文件夹，和文件，以及覆盖更新
            file.transferTo(new File(path+file.getOriginalFilename()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
